package org.webball.communication;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.Socket;

import org.webball.base.interfaces.IList;
import org.webball.base.interfaces.IMessage;
import org.webball.base.interfaces.IPitch;
import org.webball.base.interfaces.ITeam;

public class Reciever extends Thread {

	private Socket socket;
	private ObjectInputStream input;
	
	private ITeam team;
	private IPitch pitch;
	private IMessage message;
	private IList playersList;
	
	public Reciever(Socket s) throws IOException {
		socket = s;
		input = new ObjectInputStream(socket.getInputStream());
	}
	
	public void run() {
		while(!interrupted()) {
			Object obj = null;
			try {
				obj = input.readObject();
			} catch (IOException e) {
				obj = null;
			} catch (ClassNotFoundException e) {
				throw new RuntimeException(e);
			}
			
			if(obj == null) continue;
			
				 if(obj instanceof IPitch) pitch.copy((IPitch) obj);
			else if(obj instanceof IMessage) message.copy((IMessage) obj);
			else if(obj instanceof ITeam) team.copy((ITeam) obj);
			else if(obj instanceof IList) playersList.copy((IList) obj);
			
			try {
				sleep(100);
			} catch (InterruptedException e) {
				this.interrupt();
				throw new RuntimeException(e);
			}
		}
		try {
			input.close();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			input = null;
			socket = null;
		}
	}
	
	public void setMessage(IMessage m) {
		message = m;
	}
	
	public void setPitch(IPitch p) {
		pitch = p;
	}
	
	public void setTeam(ITeam t) {
		team = t;
	}
	
	public void setPlayersList(IList list) {
		playersList = list;
	}
}
